package pers.cz.javacvdemo.common;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.ToString;

import java.io.Serializable;

/**
 * ResponseResult description
 *
 * @author 
 * @version 1.0.0
 * @date 2023-06-19 12:10:49
 */
@ToString
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResponseResult<T> implements Serializable {

	private int code;

	private String msg;

	private T data;

	public int getCode() {
		return code;
	}

	public String getMsg() {
		return msg;
	}

	public T getData() {
		return data;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public void setData(T data) {
		this.data = data;
	}

	public ResponseResult() {
	}

	public ResponseResult(int code, String msg, T data) {
		this.code = code;
		this.msg = msg;
		this.data = data;
	}

	public static <T> ResponseResult<T> success(T data) {
		return new ResponseResult<>(BaseErrorEnum.SUCCESS.getCode(), BaseErrorEnum.SUCCESS.getMsg(), data);
	}

	public static <T> ResponseResult<T> success() {
		return success(null);
	}

	public static <T> ResponseResult<T> error(int code, String msg) {
		return new ResponseResult<>(code, msg, null);
	}

	public static <T> ResponseResult<T> error(Error error) {
		return new ResponseResult<>(error.getCode(), error.getMsg(), null);
	}

	public static <T> T extractDataMayException(ResponseResult<T> responseResult) {
		if (responseResult == null) {
			throw new BusinessException(BaseErrorEnum.SERVER_UNAVAILABLE);
		}
		if (responseResult.getCode() != 0) {
			throw new BusinessException(BaseErrorEnum.SERVER_UNAVAILABLE);
		}
		return responseResult.data;
	}
}
